package org.clob4eclipse.wizards;


import org.clob4eclipse.Activator;
import org.clob4eclipse.PluginData;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;

/**
 * The "New" wizard page allows setting the container for the new file as well
 * as the file name. The page will only accept file name without the extension
 * OR with the extension that matches the expected one (occ).
 */

public class OracleClobWizardPage extends WizardPage {
	private Text containerText;
	
	private Text connText;
	private Text userText;
	private Text passwordText;
	
	private Text tableNameText;
	private Text fileNameColumnText;
	private Text clobColumnNameText;

	private ISelection selection;
	private PluginData data;

	/**
	 * Constructor for SampleNewWizardPage.
	 * 
	 * @param pageName
	 */
	public OracleClobWizardPage(ISelection selection) {
		super("wizardPage");
		setTitle("Oracle Clob File");
		setDescription("This wizard querys a DB clob cell and stores it into a file in the project.");
		this.selection = selection;
		data = Activator.getPluginData();
	}
	
	

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		Label label = new Label(container, SWT.NULL);
		label.setText("&Container:");

		containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		containerText.setLayoutData(gd);
		containerText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
				data.setContainerName(containerText.getText());
			}
		});

		Button button = new Button(container, SWT.PUSH);
		button.setText("Browse...");
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleBrowse();
			}
		});
		/*
		label = new Label(container, SWT.NULL);
		label.setText("&File name:");
		
		
		fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		fileText.setLayoutData(gd);
		fileText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		*/
		// added by max
		
		
		label = new Label(container, SWT.NULL);
		label.setText("&Connection string:");
		connText = new Text(container, SWT.BORDER | SWT.SINGLE);
		connText.setSize(60, 1);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		connText.setLayoutData(gd);
		connText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				data.setConnectionString(connText.getText());
			}
		});
		// dummy label
		label = new Label(container, SWT.NULL);
		label.setText(" ");
		
		
		label = new Label(container, SWT.NULL);
		label.setText("&DB user:");
		userText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		userText.setLayoutData(gd);
		userText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				data.setUserName(userText.getText());
			}
		});
		// dummy label
		label = new Label(container, SWT.NULL);
		label.setText(" ");
		
		
		label = new Label(container, SWT.NULL);
		label.setText("&DB password:");
		passwordText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		passwordText.setLayoutData(gd);
		passwordText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				data.setPassword(passwordText.getText());
			}
		});
		
		// dummy label
		label = new Label(container, SWT.NULL);
		label.setText(" ");
		label = new Label(container, SWT.NULL);
		label.setText("&Table name:");
		tableNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		tableNameText.setLayoutData(gd);
		
		Button tablebutton = new Button(container, SWT.PUSH);
		tablebutton.setText("Browse...");
		tablebutton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleTableBrowse();
			}
		});
		
		// dummy label
		//label = new Label(container, SWT.NULL);
		//label.setText(" ");
		label = new Label(container, SWT.NULL);
		label.setText("&Column to use for the file name:");
		fileNameColumnText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		fileNameColumnText.setLayoutData(gd);
		
		Button filenamebutton = new Button(container, SWT.PUSH);
		filenamebutton.setText("Browse...");
		filenamebutton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleFileNameColumnBrowse();
			}
		});
		
		label = new Label(container, SWT.NULL);
		label.setText("&Name of the clob column:");
		clobColumnNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		clobColumnNameText.setLayoutData(gd);

		Button clobbutton = new Button(container, SWT.PUSH);
		clobbutton.setText("Browse...");
		clobbutton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleClobColumnBrowse();
			}
		});
		// end max
		
		initialize();
		dialogChanged();
		setControl(container);
	}

	/**
	 * Tests if the current workbench selection is a suitable container to use.
	 */
	private void initialize() {
		if (selection != null && selection.isEmpty() == false
				&& selection instanceof IStructuredSelection) {
			IStructuredSelection ssel = (IStructuredSelection) selection;
			if (ssel.size() > 1)
				return;
			Object obj = ssel.getFirstElement();
			if (obj instanceof IResource) {
				IContainer container;
				if (obj instanceof IContainer)
					container = (IContainer) obj;
				else
					container = ((IResource) obj).getParent();
				containerText.setText(container.getFullPath().toString());
			}
		}
		
		connText.setText(data.getConnectionString());
		userText.setText(data.getUserName());
		passwordText.setText(data.getPassword());
		clobColumnNameText.setText(data.getClobColumnName());
		fileNameColumnText.setText(data.getFileNameColumn());
		tableNameText.setText(data.getTableName());
	}

	/**
	 * Uses the standard container selection dialog to choose the new value for
	 * the container field.
	 */
	private void handleBrowse() {
		ContainerSelectionDialog dialog = new ContainerSelectionDialog(
				getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
				"Select new file container");
		if (dialog.open() == ContainerSelectionDialog.OK) {
			Object[] result = dialog.getResult();
			if (result.length == 1) {
				containerText.setText(((Path) result[0]).toString());
			}
		}
	}
	
	private void handleTableBrowse(){
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new LabelProvider());
		dialog.setTitle("Select a table with the clob column");
		
		String query = "select distinct TABLE_NAME from USER_TAB_COLUMNS t where DATA_TYPE = 'CLOB'";
		DbSelectionListBean tlb = new DbSelectionListBean(Activator.getPluginData(), query);
		
		if (tlb.getObjectArray() == null) {
			dialog.setMessage("No tables with CLOB column found!!");
		} else {
			dialog.setMessage("Select a String (* = any string, ? = any char):");
			dialog.setElements(tlb.getObjectArray());
		}
		if (dialog.open() == Window.OK){
			tableNameText.setText(dialog.getFirstResult().toString());
		}
	}
	
	private void handleClobColumnBrowse(){
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new LabelProvider());
		dialog.setTitle("Select the clob column");
		
		String query = "select COLUMN_NAME from USER_TAB_COLUMNS t where TABLE_NAME = '"+tableNameText.getText()+"' and  DATA_TYPE = 'CLOB'";
		DbSelectionListBean tlb = new DbSelectionListBean(Activator.getPluginData(), query);
		
		if (tlb.getObjectArray() == null) {
			dialog.setMessage("No CLOB column found!!");
		} else {
			dialog.setMessage("Select a String (* = any string, ? = any char):");
			dialog.setElements(tlb.getObjectArray());
		}
		if (dialog.open() == Window.OK){
			clobColumnNameText.setText(dialog.getFirstResult().toString());
		}	
	}
	
	private void handleFileNameColumnBrowse(){
		ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new LabelProvider());
		dialog.setTitle("Column to use for the file name");
		
		String query = "select COLUMN_NAME from USER_TAB_COLUMNS t where TABLE_NAME = '"+tableNameText.getText()+"' and  DATA_TYPE != 'CLOB'";
		DbSelectionListBean tlb = new DbSelectionListBean(Activator.getPluginData(), query);
		
		if (tlb.getObjectArray() == null) {
			dialog.setMessage("No other column found!!");
		} else {
			dialog.setMessage("Select a String (* = any string, ? = any char):");
			dialog.setElements(tlb.getObjectArray());
		}

		if (dialog.open() == Window.OK){
			fileNameColumnText.setText(dialog.getFirstResult().toString());
		}	
	}

	/**
	 * Ensures that both text fields are set.
	 */
	private void dialogChanged() {
		IResource container = ResourcesPlugin.getWorkspace().getRoot()
				.findMember(new Path(getContainerName()));
		if (getContainerName().length() == 0) {
			updateStatus("File container must be specified");
			return;
		}
		if (container == null
				|| (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
			updateStatus("File container must exist");
			return;
		}
		if (!container.isAccessible()) {
			updateStatus("Project must be writable");
			return;
		}
		updateStatus(null);
	}

	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}

	public PluginData getPluginData(){
		PluginData data = Activator.getPluginData();
		data.setContainerName(containerText.getText());
		data.setConnectionString(connText.getText());
		data.setUserName(userText.getText());
		data.setPassword(passwordText.getText());
		data.setClobColumnName(clobColumnNameText.getText());
		data.setFileNameColumn(fileNameColumnText.getText());
		data.setTableName(tableNameText.getText());
		
		Activator.setPluginData(data);
		return data;
	}
	
	public String getContainerName() {
		return containerText.getText();
	}

	public String getConnText() {
		return connText.getText();
	}

	public String getUserText() {
		return userText.getText();
	}

	public String getPasswordText() {
		return passwordText.getText();
	}
}